package hqu.cst.XAH.controller;

import hqu.cst.XAH.pojo.Movie;
import hqu.cst.XAH.service.MovieService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;


import org.springframework.web.bind.annotation.*;
import org.springframework.http.*;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

@RestController
@RequestMapping("/movies")
@Tag(name = "电影查看", description = "电影管理接口")
public class MovieController {
    @Autowired
    private MovieService movieService;

    @GetMapping
    public List<Movie> getAllMovies() {
        return movieService.getAllMovies();
    }

    @GetMapping("/{id}")
    public ResponseEntity<Movie> getMovieById(@PathVariable Long id) {
        return movieService.getMovieById(id);
    }

    @PostMapping("/add")
    public ResponseEntity<String> addMovie(@RequestBody @Valid Movie movie) {
        movieService.addMovie(movie);
        return ResponseEntity.ok("Movie added successfully.");
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> deleteMovie(@PathVariable Long id) {
        movieService.deleteMovie(id);
        return ResponseEntity.ok("Movie deleted successfully.");
    }

    @PostMapping(value = "/uploadPoster/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "Upload a poster for the movie")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Poster uploaded successfully"),
            @ApiResponse(responseCode = "500", description = "Failed to upload poster")
    })
    public ResponseEntity<String> uploadPoster(
            @PathVariable Long id,
            @RequestParam("file") MultipartFile file) {
        try {
            movieService.uploadPoster(id, file);
            return ResponseEntity.ok("Poster uploaded successfully.");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload poster: " + e.getMessage());
        }
    }

    @GetMapping("/downloadPoster/{id}")
    @Operation(summary = "Download the poster of the movie")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "Poster file"),
            @ApiResponse(responseCode = "404", description = "Poster not found")
    })
    public ResponseEntity<Resource> downloadPoster(@PathVariable Long id) {
        try {
            Resource file = movieService.downloadPoster(id);

            // 确定文件的 MIME 类型
            String contentType;
            try {
                contentType = Files.probeContentType(Paths.get(file.getURI()));
            } catch (IOException e) {
                contentType = "application/octet-stream"; // 默认类型
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
                    .body(file);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
    }

}
